package com.icss.filter;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.icss.beans.User;

/**
 * @author 韦锦良
 *　类的作用：权限过滤器，针对不同的方法应该有的权限进行过滤
 * 最后修改时间：2010-3-28　上午11:48:05
 * 最后的改动内容：初始版本
 */
public class AuthFilter implements Filter {

	//论坛普通用户在数据中的权限
	private static final String BBS_USER = "1";

	//论坛管理员在数据中的权限
	private static final String BBS_ADMIN = "2";

	private static final String OFFICE_USER = "办公系统普通用户";

	private static final String OFFICE_ADMIN = "办公系统管理员";

	private static final String ANONYMOUS = "匿名用户";

	//保存权限配置文件
	private Document permissionDoc = null;

	public void init(FilterConfig filterConfig) {

		//创建一个xml解析器
		SAXReader reader = new SAXReader();

		//读取权限配置文件
		try {

			String path = filterConfig.getServletContext().getRealPath("/") + "upload/";
			String realPath = path + "permission.xml";
			permissionDoc = reader.read(new File(realPath));
		} catch (DocumentException e) {
			e.printStackTrace();
		}

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		User user = null;
		String power = null;
		
		//办公系统权限
		user = (User) httpRequest.getSession().getAttribute("User");
		if (null != user) {
			power = user.getPower();
		}
		
		//论坛权限
		String pid = (Integer) httpRequest.getSession(false).getAttribute("pid") + "";
		String uri = httpRequest.getRequestURI().toString();

		try {
			
		
			if (!isIgnoreRequest(uri, httpRequest.getContextPath())) {
				response.setContentType("text/html");
				PrintWriter out = null;
				try {
					out = response.getWriter();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				//获得请求的uri
				String requestURI = httpRequest.getRequestURI();
				
				//获得请求的是哪个servlet
				String requestServlet = requestURI.substring(requestURI.lastIndexOf("/") + 1).trim();
				
				//从配置文件获得请求的servlet相应的
				Element requestElement = (Element) permissionDoc.selectSingleNode("//permission/servlet[@name='"
						+ requestServlet + "']");
				
				//配置文件获得区别请求参数
				String requestMethod = requestElement.attributeValue("requestMethod");
				String paramName = request.getParameter(requestMethod);
				String xPath = "//permission/servlet[@name='" + requestServlet + "']/request[@name='" + paramName
						+ "']";
				String permission = ((Element) requestElement.selectSingleNode(xPath)).getText().trim();

				//假如要求的权限是匿名用户，直接不用再验证了
				if (permission.equals(AuthFilter.ANONYMOUS)) {
					filterChain.doFilter(request, response);
					return;
				} else if (permission.equals(AuthFilter.BBS_USER)) {//如果是论坛普通用户

					if (null == pid) {
						out.write("<script>alert('你还没有登录，请先登录！');</script>");
						out.close();
						return;
					}

					if (pid.equals(AuthFilter.BBS_USER) || pid.equals(AuthFilter.BBS_ADMIN)) {
						filterChain.doFilter(request, response);
						return;
					} else {
						out.write("<script>alert('你没有足够的权限进行此操作，请和管理员联系');</script>");
						out.close();
						return;
						//权限不够
					}

				} else if (permission.equals(AuthFilter.BBS_ADMIN)) {

					if (null == pid) {
						out.write("alert('你还没有登录，请先登录！');</script>");
						out.close();
						return;
					}

					if (pid.equals(AuthFilter.BBS_ADMIN)) {
						filterChain.doFilter(request, response);
						return;
					} else {
						out.write("<script>alert('你没有足够的权限进行此操作，请和管理员联系');</script>");
						out.close();
						return;
						//权限不够
					}

				} else if (permission.equals(AuthFilter.OFFICE_USER)) {

					if (null == power) {
						out.write("<script>alert('你还没有登录，请先登录！');</script>");
						out.close();
						return;
					}

					if (power.equals(AuthFilter.OFFICE_USER) || power.equals(AuthFilter.OFFICE_ADMIN)) {
						filterChain.doFilter(request, response);
						return;
					} else {
						out.write("<script>alert('你没有足够的权限进行此操作，请和管理员联系');</script>");
						out.close();
						return;
						//权限不够
					}

				} else if (permission.equals(AuthFilter.OFFICE_ADMIN)) {

					if (null == power) {
						out.write("<script>alert('你还没有登录，请先登录！');</script>");
						out.close();
						return;
					}

					if (power.equals(AuthFilter.OFFICE_ADMIN)) {
						filterChain.doFilter(request, response);
						return;
					} else {
						out.write("<script>alert('你没有足够的权限进行此操作，请和管理员联系');</script>");
						out.close();
						return;
						//权限不够
					}

				}

			}

			filterChain.doFilter(request, response);

		} catch (ServletException sx) {
			sx.printStackTrace();
		} catch (IOException iox) {
			iox.printStackTrace();
		}

	}

	//判断请求的uri是否用过滤
	public boolean isIgnoreRequest(String uri, String contextPath) {
		if (uri.contains(".")) {
			return true;
		}
		if (uri.equals(contextPath + "/")) {
			return true;
		}
		return false;
	}

	public void destroy() {
		
	}

}
